package com.jlnk.picassodemo.views;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jlnk.picassodemo.adapter.CustomArrayAdapter;
import com.jlnk.picassodemo.entity.ImageEntity;
import com.jlnk.picassodemo.R;
import com.squareup.picasso.Picasso;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private List<ImageEntity> imageList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.list_view);
        fetchData();
    }

    private void fetchData() {
        new Thread(() -> {
            try {
                String url = "https://peapix.com/bing/feed";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                Response response = client.newCall(request).execute();
                String jsonData = response.body().string();
                Type listType = new TypeToken<List<ImageEntity>>(){}.getType();
                List<ImageEntity> tempList = new Gson().fromJson(jsonData, listType);
                if (tempList != null) {
                    runOnUiThread(() -> {
                        imageList.addAll(tempList);
                        CustomArrayAdapter adapter = new CustomArrayAdapter(MainActivity.this, imageList);
                        listView.setAdapter(adapter);
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}